package com.howard.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;

import com.howard.dao.UserDao;
import com.howard.entity.User;
import com.howard.exception.LoginException;
import com.howard.service.LoginService;
import com.howard.vo.Login;

/**
 * Login Service
 * @author <a href="mailto:howard.he0329@gmail.com">Howard.He</a>
 * @since 2011-06-14
 * @version 1.0
 *
 */
@Service
public class LoginServiceImpl implements LoginService {

	private static final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

	@Autowired
	private UserDao userDao;

	@Override
	public User doLogin(final Login login) throws LoginException {
		if(login == null) {
			throw new IllegalArgumentException("argument Login can not be null");
		}
		if(StringUtils.isBlank(login.getLoginName()) || StringUtils.isBlank(login.getPassword())) {
			throw new IllegalArgumentException("argument Login incorrect");
		}
		User user = null;
		try {
			user = userDao.queryUserByName(login.getLoginName());
			//验证密码是否一致
			if(!StringUtils.equals(user.getPassword(), login.getPassword()))
				throw new LoginException("password incorrect");
			return user;
		} catch (DataAccessException e) {
			logger.error("doLogin operation", e);
			if(e instanceof EmptyResultDataAccessException)
				throw new LoginException("user not exists", e);
			else
				throw new LoginException(e);
		}
	}
}
